from rest_framework import serializers

from .models import BookInfo
# 自定义序列化器


class PeopleInfoSerializer(serializers.Serializer):
    """定义多的这一方，通过一的那一方都返回什么"""
    # 英雄序列化器
    name = serializers.CharField()
    description = serializers.CharField()
    # book = serializers.PrimaryKeyRelatedField(read_only=True, many=True)  错...你自己看看写的什么参数
    # book = serializers.StringRelatedField(read_only=True, many=True)  错
    # book = serializers.PrimaryKeyRelatedField()  错

    # book = serializers.PrimaryKeyRelatedField(read_only=True)  # 返回ID
    book = serializers.StringRelatedField()  # 返回 __Str__方法返回内容


def readcount_valid(value):
    print(value)
    print('单个字段验证方法的补充：对当前字段，添加一个验证方法')


class BookSerializer(serializers.Serializer):

    # 序列化返回字段
    name = serializers.CharField()
    pub_date = serializers.DateField()
    # pub_date = serializers.DateField(validators=pub_date_valid)
    # required 默认是True，改成False，意为验证时非必传
    # validators=[readcount_valid] 要是列表
    readcount = serializers.IntegerField(required=False, validators=[readcount_valid])  # required 默认是True，改成False，意为验证时非必传
    # readcount = serializers.IntegerField(required=False)  # required 默认是True，改成False，意为验证时非必传
    commentcount =serializers.IntegerField(default=20)
    # 返回关联的英雄id  PrimaryKeyRelatedField  read_only=True:只做返回，不做校验
    # peopleinfo_set = serializers.PrimaryKeyRelatedField(read_only=True, many=True)

    # 将__str__返回的值，返回到前端  StringRelatedField
    # peopleinfo_set = serializers.StringRelatedField(read_only=True, many=True)

    # peopleinfo_set = PeopleInfoSerializer(many=True)

    # 单一字段验证 (validate_要验证的字段)
    # 序列化特定的抛出异常的方法
    # def validate_name(self, bname):
    #     if bname == 'python':
    #         raise serializers.ValidationError('不能是python')

        # return bname

    # 多字段验证（函数名是固定不变的）
    def validate(self, attrs):

        if attrs['readcount'] < attrs['commentcount']:
            raise serializers.ValidationError('评论量不能大于阅读量')
        return attrs

    # # 保存数据 方式一
    # def create(self, validated_data):
    #     book = BookInfo.objects.create(
    #         name=validated_data['name'],
    #         pub_date=validated_data['pub_date'],
    #         readcount=validated_data['readcount'],
    #         commentcount=validated_data['commentcount']
    #
    #     )
    #     return book

    # 保存数据 方式二： 拆包
    def create(self, validated_data):
        book = BookInfo.objects.create(**validated_data)
        return book

    def update(self, instance, validated_data):
        instance.name = validated_data['name']
        instance.readcount = validated_data['readcount']
        instance.save()
        return instance


class BookModelSerializer(serializers.Serializer):
    """模型类序列化器"""
    # 修改、增加 选项参数的使用
    # 方式一：指明显示（也可以增加字段）
    commentcount = serializers.IntegerField(min_value=0)
    sms_code = serializers.CharField(max_length=6, min_length=6)
    class Meta:
        model=BookInfo  # 指定生成字段的模型类
        # fields = ('name', 'pub_date', 'readcount', 'commentcount')  # 指定模型类中的字段
        fields = '__all__'  # 模型类中的所有字段
        # exclude = ('commentcount')  # 取反操作
        # read_only_fields = ('name',)

        # 方式二：extra_kwargs 添加修改字段的选项参数
        extra_kwargs = {
            'name': {
                'max_length': 20,
                'min_length': 4
            }
            # 'sms_code': {
            #     'max_length': 6,
            #     'min_length': 6
            # }
        }





